package org.example.utils.post.reply;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.dao.dao.post.PReplyDao;
import org.example.dao.dao.user.UUserDao;
import org.example.dao.dto.commom.UserInfo;
import org.example.dao.dto.post.PCommentDto;
import org.example.dao.dto.post.PReplyDto;
import org.example.dao.dto.user.UserDto;
import org.example.dao.entity.post.PComment;
import org.example.dao.entity.post.PReply;
import org.example.dao.entity.user.UUser;
import org.example.skytool.commom.ContextUtil;
import org.example.skytool.redis.RedisConstants;
import org.example.utils.post.comment.RedisCommentService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class ExtendReplyService {

    @Resource
    private PReplyDao pReplyDao;

    @Resource
    private ContextUtil contextUtil;

    @Resource
    private UUserDao uUserDao;

    @Resource
    private RedisReplyService redisReplyService;

    public IPage<PReplyDto> getReplyDtoPage(IPage<PReply> pPosts) {
        List<PReplyDto> list = new ArrayList<>();
        for (PReply reply : pPosts.getRecords()) {
            PReplyDto replyDto = createReplyDto(reply);
            list.add(replyDto);
        }
        IPage<PReplyDto> iPage = new Page<>();
        iPage.setRecords(list);
        iPage.setTotal(pPosts.getTotal());
        iPage.setPages(pPosts.getPages());
        iPage.setCurrent(pPosts.getCurrent());
        iPage.setSize(pPosts.getSize());
        return iPage;
    }

    public PReplyDto createReplyDto(PReply reply) {
        PReplyDto replyDto = new PReplyDto();
        redisReplyService.getReplyCache(reply);
        replyDto.setPReply(reply);
        Long userPostId = reply.getReceiverId();
        UUser user = uUserDao.selectById(userPostId);
        UserInfo userInfoReceiver = new UserInfo(user);
        UserDto userDto = contextUtil.getLoginUser();
        UserInfo userInfoSender = new UserInfo(userDto);
        replyDto.setReceiverUser(userInfoReceiver);
        replyDto.setSenderUser(userInfoSender);
        String replyId = reply.getId().toString();
        String userId = contextUtil.getId().toString();
        replyDto.setIsLike(redisReplyService.judgeIsMember(replyId, userId));
        return replyDto;
    }


    public LambdaQueryWrapper<PReply> getLambdaQueryWrapper() {
        LambdaQueryWrapper<PReply> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PReply::getIsValid, 1);
        lambdaQueryWrapper.orderBy(true, false, PReply::getCreateTime);
        return lambdaQueryWrapper;
    }


}
